package com.sx.zongzhi.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.MultiImageAdapter;
import com.sx.zongzhi.adapter.SpinnerPubAdapter;
import com.sx.zongzhi.bean.DisputeBean;
import com.sx.zongzhi.bean.DisputeDetailBean;
import com.sx.zongzhi.bean.EventTypeBean;
import com.sx.zongzhi.bean.GlobalBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.PartiesBean;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.PublicBean;
import com.sx.zongzhi.net.ServiceFactory;
import com.sx.zongzhi.presenter.DisputeAddPest;
import com.sx.zongzhi.presenter.DisputeDetailPest;
import com.sx.zongzhi.presenter.PublicListPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.FileUtils;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IDisputeAddView;
import com.sx.zongzhi.view.IDisputeDetailView;
import com.sx.zongzhi.view.IPublicBeanView;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.AudioDialog;
import com.sx.zongzhi.widget.LoadDialog;
import com.zero.smallvideorecord.MediaRecorderActivity;
import com.zero.smallvideorecord.model.MediaRecorderConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 编辑矛盾纠纷
 */
public class DisputeEditActivity extends BaseActivity implements View.OnClickListener
        ,IPublicBeanView ,IDisputeAddView,IDisputeDetailView ,UploadFileView{

    @BindView(R.id.et_EventName) EditText et_EventName;
    //发生网格
    @BindView(R.id.tv_HappenGrid) TextView tv_HappenGrid;
    @BindView(R.id.et_HappenLocation) EditText et_HappenLocation;
    //发生日期
    @BindView(R.id.tv_Data) TextView tv_Data;
    //涉及单位
    @BindView(R.id.et_InvolveCompany) EditText et_InvolveCompany;
    //涉及人数
    @BindView(R.id.et_InvolveNum) EditText et_InvolveNum;
    //主要当事人
    @BindView(R.id.et_Litigant) TextView tv_Litigant;
    @BindView(R.id.tv_EventType) TextView tv_EventType;
    @BindView(R.id.sp_EventScale) Spinner scaleSpinner;
    @BindView(R.id.sp_EventSource) Spinner sourceSpinner;
    @BindView(R.id.et_EventDescribe) EditText et_EventDescribe;
    @BindView(R.id.et_CheckSuggest) EditText et_CheckSuggest;
    //事件发展预测
    @BindView(R.id.et_Forecast) EditText et_Forecast;
    //调节措施
    @BindView(R.id.et_Measures) EditText et_Measures;
    @BindView(R.id.rv_imageRV) RecyclerView rvImageRV;
    private AudioDialog audioDialog;

    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();
    /**上传后的地址所选文件*/
    private List<String> fileList;
    private List<String> removeList;
    private PopupWindow selectPop;

    private DisputeDetailBean disputeAddBean;
    /**公共字段获取 事件规模 事件来源*/
    private PublicListPest publicListPest;
    private DisputeDetailPest detailPest;
    //事件性质/事件来源
    private List<GlobalBean> eventScaleList,eventSourceList;
    private List<PartiesBean> partiesBeen;
    private Disposable disposable;
    /**事件主键*/
    private DisputeBean.RowsBean rowsBean;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_dispute_add_);
        setTitleName("矛盾纠纷修改");
        rowsBean= (DisputeBean.RowsBean) getIntent().getSerializableExtra("DisputeBean.RowsBean");
        setTitleRight(R.string.submit);
        ButterKnife.bind(this);
        publicListPest=new PublicListPest(this);
        detailPest=new DisputeDetailPest(this);
        initView();
    }

    private void initView() {
        LoadDialog.show(this,"获取详情信息...");
        detailPest.getDisputeDetail(rowsBean.getId(),"",0);
        publicListPest.getPublicList("事件性质");//事件规模
        publicListPest.getPublicList("事件来源方式");//事件来源
        rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        adapter = new MultiImageAdapter(this, mAddPicClickListener);
        adapter.setList(selectList);
        rvImageRV.setAdapter(adapter);
        adapter.setOnItemClickListener(new MultiImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position, View v) {
                String type = selectList.get(position).getSuffixType();
                String path = selectList.get(position).getPath();
                if(".mp4".equalsIgnoreCase(type)){
                    startActivity(new Intent(DisputeEditActivity.this, VideoPlayerActivity.class).putExtra(
                            "path",path));
                }else if(".wav".equalsIgnoreCase(type) || ".amr".equalsIgnoreCase(type)){
                    if (audioDialog!=null){
                        audioDialog.startPlay(path);
                    }
                }else if (".jpeg".equalsIgnoreCase(type)||".png".equalsIgnoreCase(type)||
                        ".jpg".equalsIgnoreCase(type)){
                    startActivity(new Intent(DisputeEditActivity.this, ImagePlayActivity.class).putExtra(
                            "path", path));
                }else {
                    ToastUtils.showToast(DisputeEditActivity.this,"不能查看文件");
                }
            }
        });
        adapter.setOnDeleteNetFileClickListener(new MultiImageAdapter.OnDeleteNetFileClickListener() {
            @Override
            public void deleteFileId(String fileId) {
                if (removeList==null){
                    removeList=new ArrayList<String>();
                }
                removeList.add(fileId);
            }
        });
        //订阅筛选组织机构
        disposable= MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent msg) throws Exception {
                        if ("DisputeEditActivity".equals(msg.getRequest())){
                            if (msg.getType()==0) {
                                OrganizingBean bean = (OrganizingBean) msg.getMsg();
                                if (bean != null) {
                                    tv_HappenGrid.setText(bean.getName());
                                    DisputeDetailBean.OccurOrgBean orgBean = disputeAddBean.getOccurOrg();
                                    if (orgBean != null) {
                                        orgBean.setId(bean.getId());
                                    } else {
                                        orgBean = new DisputeDetailBean.OccurOrgBean();
                                        orgBean.setId(bean.getId());
                                    }
                                    disputeAddBean.setOccurOrg(orgBean);
                                }
                            }
                            if (msg.getType()==1){
                                partiesBeen= (List<PartiesBean>) msg.getMsg();
                                if (partiesBeen!=null&&partiesBeen.size()>0){
                                    int count=partiesBeen.size();
                                    String str="";
                                    for (int i=0;i<count;i++){
                                        PartiesBean bean=partiesBeen.get(i);
                                        if (i==count-1){
                                            str=str+bean.getPartyName();
                                        }else {
                                            str=str+bean.getPartyName()+',';
                                        }
                                    }
                                    tv_Litigant.setText(str);
                                }
                            }
                        }
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable.isDisposed()){
            disposable.dispose();
        }
    }

    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            if (max > 0) {
                showPopupSelect();
            } else {
                ToastUtils.showToast(DisputeEditActivity.this,"最多上传三项");
            }
        }
    };


    @OnClick({R.id.tv_right,R.id.tv_Data,R.id.et_Litigant,R.id.tv_EventType,R.id.tv_HappenGrid})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_right:
                submit();
                break;
            case R.id.tv_HappenGrid:
                startActivity(new Intent(this, OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT,"DisputeEditActivity"));
                break;
            case R.id.tv_Data:
                BaseUtil.createDataPop(this,tv_Data);
                break;
            case R.id.et_Litigant://新增当事人
                Intent intent=new Intent(DisputeEditActivity.this,AddLitigantActivity.class);
                intent.putExtra(Global.ACTIVITY_FRAGMENT,"DisputeEditActivity");
                if (disputeAddBean!=null){
                    intent.putExtra("DisputeDetailBean",disputeAddBean);
                }
                startActivity(intent);
                break;
            case R.id.tv_EventType://事件类别
                startActivityForResult(new Intent(DisputeEditActivity.this,EventTypeActivity.class),4446);
                break;

        }
    }

    /**
     * 提交
     */
    private void submit() {
        LoadDialog.show(this,"正在提交...");
        String eventName=et_EventName.getText().toString().trim();
        if (eventName.length()<2||eventName.length()>30){
            et_EventName.setError("事件名称2~30个字");
            return;
        }
        if (disputeAddBean.getOccurOrg()==null){
            ToastUtils.showToast(this,"请选择发生网格");
            return;
        }
        String location=et_HappenLocation.getText().toString().trim();
        if (location.length()>30||location.length()<1){
            et_HappenLocation.setError("30个字以内");
            return;
        }
        String time=tv_Data.getText().toString();
        if (BaseUtil.isEmpty(time)){
            ToastUtils.showToast(this,"请选择发生时间");
            return;
        }
        String company=et_InvolveCompany.getText().toString();
        String nom=et_InvolveNum.getText().toString();
        if (BaseUtil.isEmpty(nom)){
            et_InvolveNum.setError("涉及人数大于1");
            return;
        }
        if (disputeAddBean.getIssueTypeId()==null){
            ToastUtils.showToast(this,"请选择事件类别");
            return;
        }
        String scale=((GlobalBean)scaleSpinner.getSelectedItem()).getId();
        String source=((GlobalBean)sourceSpinner.getSelectedItem()).getId();
        String  describe=et_EventDescribe.getText().toString().trim();
        if (describe.length()<1||describe.length()>1000){
            et_EventDescribe.setError("1~1000字以内");
            return;
        }
        String  suggest=et_CheckSuggest.getText().toString().trim();
        String  forecast=et_Forecast.getText().toString().trim();
        String  measures=et_Measures.getText().toString().trim();
        disputeAddBean.setName(eventName);
        disputeAddBean.setOccurPlace(location);
        disputeAddBean.setOccurDate(time);
        disputeAddBean.setRelatedUnit(company);
        disputeAddBean.setRelatePeopleCount(Integer.parseInt(nom));

        GlobalBean issueKindBean=new GlobalBean();
        issueKindBean.setId(scale);
        disputeAddBean.setIssueKind(issueKindBean);
        GlobalBean eventSourceBean=new GlobalBean();
        eventSourceBean.setId(source);
        disputeAddBean.setEventSource(eventSourceBean);
        disputeAddBean.setIssueContent(describe);
        disputeAddBean.setEvaluateOpinion(suggest);
        disputeAddBean.setDevelopForecast(forecast);
        disputeAddBean.setAdjustMeasures(measures);

        if (selectList.size()>0){
            List<File> files = new ArrayList<>();
            for (PhotoBean photoBean:selectList){
                if (!photoBean.getPath().startsWith("http://")){
                    files.add(new File(photoBean.getPath()));
                }
            }
            if (files.size()>0){
                LoadDialog.show(this,"正在上传文件...");
                new UploadFilePest(this).uploadFile(this,files);
            }else {
                submitDone();
            }
        }else {
            submitDone();
        }

    }

    private void submitDone() {
        DisputeAddPest disputeAddPest=new DisputeAddPest(this);
        disputeAddPest.disputeAdd("updateIssue.action",rowsBean.getId(),
                disputeAddBean,partiesBeen, fileList,removeList);
    }


    /**
     * 显示选择文件的弹窗
     */
    private void showPopupSelect() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_file, null);
        if (selectPop == null) {
            selectPop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            selectPop.setTouchable(true);
            selectPop.setOutsideTouchable(false);
            selectPop.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
        }
        view.findViewById(R.id.tv_Picture).setOnClickListener(this);
        view.findViewById(R.id.tv_File).setOnClickListener(this);
        view.findViewById(R.id.tv_Audio).setOnClickListener(this);
        view.findViewById(R.id.tv_Video).setOnClickListener(this);
        view.findViewById(R.id.tv_Cancel).setOnClickListener(this);
        selectPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_Picture:
                int max = 3 - selectList.size();
                    PictureSelector.create(this)
                            .openGallery(PictureMimeType.ofImage())
                            .selectionMode(PictureConfig.MULTIPLE)
                            .maxSelectNum(max)// 最大图片选择数量 int
                            .compress(true)
                            .compressGrade(Luban.CUSTOM_GEAR)
                            .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.tv_File://选文件
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                try {
                    startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), 4447);
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(this, "Please install a File Manager.",  Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_Audio:
                if (audioDialog==null){
                    audioDialog=new AudioDialog(DisputeEditActivity.this);
                    audioDialog.setCancelable(false);
                    audioDialog.getAudioBack(new AudioDialog.AudioCallback() {
                        @Override
                        public void getData(String filePath, int countdown) {
                            PhotoBean photoBean = new PhotoBean(filePath, ".amr");
                            selectList.add(photoBean);
                            if (adapter != null) adapter.notifyDataSetChanged();
                        }
                    });
                }
                audioDialog.show(audioDialog.AUDIO_RECODERD);
                break;
            case R.id.tv_Video:
                MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                        .smallVideoWidth(640)
                        .smallVideoHeight(480)
                        .recordTimeMax(10 * 1000)
                        .maxFrameRate(20)
                        .minFrameRate(8)
                        .captureThumbnailsTime(1)
                        .videoBitrate(580000)
                        .build();
                MediaRecorderActivity.goSmallVideoRecorder(this, DisputeAddActivity.class.getName(), config);
                break;
            case R.id.tv_Cancel:
                break;
        }
        selectPop.dismiss();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 4446://选择事件类别
                    EventTypeBean.TypesBean typesBean= (EventTypeBean.TypesBean) data.getSerializableExtra("EventTypeBeanID");
                    tv_EventType.setText(data.getStringExtra("PrentName")+"-"+typesBean.getTypeName());
                    disputeAddBean.setIssueTypeId(typesBean.getTypeId());
                    break;
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
                case MediaRecorderActivity.FOR_RESULT://拍视频
                    String videoUri = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                    if (!TextUtils.isEmpty(videoUri)) {
                        String type = videoUri.substring(videoUri.lastIndexOf("."));
                        selectList.add(new PhotoBean(videoUri, type));
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
                case 4447://选择文件
                    Uri selectedMediaUri = data.getData();
                    String path = FileUtils.getPath(this, selectedMediaUri);
                    if (!BaseUtil.isEmpty(path)) {
                        String type = path.substring(path.lastIndexOf("."));
                        if (".txt".equalsIgnoreCase(type)||".docx".equalsIgnoreCase(type)||".doc".equalsIgnoreCase(type)
                                ||".pdf".equalsIgnoreCase(type)||".xls".equalsIgnoreCase(type)){

                            selectList.add(new PhotoBean(path, type));
                            if (adapter != null) adapter.notifyDataSetChanged();
                        }else {
                            ToastUtils.showToast(this,"不支持当前类型文件上传");
                        }
                    }else {
                        ToastUtils.showToast(this,"文件异常请重新选择");
                    }
                    break;
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,message);
    }

    @Override
    public void getPublicList(PublicBean publicBean) {
        if ("事件性质".equals(publicBean.getDomainName())){
            eventScaleList=publicBean.getDicts();
            if (eventScaleList!=null){
                SpinnerPubAdapter adapter=new SpinnerPubAdapter(this,R.layout.item_text,eventScaleList);
                scaleSpinner.setAdapter(adapter);
                if (disputeAddBean!=null){
                    showEventScale();
                }
            }
        }
        if ("事件来源方式".equals(publicBean.getDomainName())){
            eventSourceList=publicBean.getDicts();
            if (eventSourceList!=null){
                SpinnerPubAdapter adapter=new SpinnerPubAdapter(this,R.layout.item_text,eventSourceList);
                sourceSpinner.setAdapter(adapter);
                if (disputeAddBean!=null) {
                    showEventSource();
                }
            }
        }
    }

    /**
     * 添加成功回调
     */
    @Override
    public void addDispute(DisputeDetailBean addBean) {
        LoadDialog.dismiss(this);
        if (addBean!=null){
            ToastUtils.showToast(this,"修改成功");
            MyRxBus.get().post(new MsgEvent<>("DisputePendingActivity",1,"修改成功"));
            finish();
        }
    }

    /**
     * 获取详细信息
     */
    @Override
    public void getDisputeDetail(DisputeDetailBean detailBean) {
        LoadDialog.dismiss(this);
        disputeAddBean=detailBean;
        setViews();
    }

    public void setViews() {
        et_EventName.setText(disputeAddBean.getName());
        tv_HappenGrid.setText(disputeAddBean.getOccurOrg().getOrgName());
        et_HappenLocation.setText(disputeAddBean.getOccurPlace());
        tv_Data.setText(disputeAddBean.getOccurDate());
        et_InvolveCompany.setText(disputeAddBean.getRelatedUnit());
        et_InvolveNum.setText(disputeAddBean.getRelatePeopleCount()+"");
        if (disputeAddBean.getParties()!=null&&disputeAddBean.getParties().size()>0){
            String str="";
            int count=disputeAddBean.getParties().size();
            for (int i=0;i<count;i++){
                str=str+disputeAddBean.getParties().get(i).getPartyName()+" ";
            }
            tv_Litigant.setText(str);
        }
        tv_EventType.setText(disputeAddBean.getIssueTypeName());
        if (eventScaleList!=null){
            showEventScale();
        }
        if (eventSourceList!=null){
            showEventSource();
        }
        et_EventDescribe.setText(disputeAddBean.getIssueContent());
        et_CheckSuggest.setText(disputeAddBean.getEvaluateOpinion());
        et_Forecast.setText(disputeAddBean.getDevelopForecast());
        et_Measures.setText(disputeAddBean.getAdjustMeasures());
        if (disputeAddBean!=null&&disputeAddBean.getFiles()!=null&&disputeAddBean.getFiles().size()>0){
            selectList.clear();
            for (PhotoBean photoBean:disputeAddBean.getFiles()){
                photoBean.setPath(ServiceFactory.NEW_API_BASE_URL + File.separator + photoBean.getPath());
                selectList.add(photoBean);
            }
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 显示事件来源
     */
    private void showEventSource() {
        if (disputeAddBean.getEventSource()!=null) {
        for (int i=0;i<eventSourceList.size();i++){
                if (eventSourceList.get(i).getId().equals(disputeAddBean.getEventSource().getId())) {
                    sourceSpinner.setSelection(i);
                }
            }
        }
    }

    /**
     * 显示事件规模
     */
    private void showEventScale() {
        if (disputeAddBean.getIssueKind()!=null) {
            for (int i = 0; i < eventScaleList.size(); i++) {
                if (eventScaleList.get(i).getId().equals(disputeAddBean.getIssueKind().getId())) {
                    scaleSpinner.setSelection(i);
                }
            }
        }
    }


    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        if (beans!=null&&beans.size()>0){
            if (fileList==null){
                fileList=new ArrayList<>();
            }
            for (PhotoBean photoBean:beans){
                fileList.add(photoBean.getPath());
            }
            submitDone();
        }else {
            LoadDialog.dismiss(this);
            ToastUtils.showToast(this,"文件上传异常");
        }
    }
}
